unit uPacker;

interface

const
  S_Packer = 'packer.dll';
procedure PKG_InitLib;
function PKG_UpdateFile(archName: string; archFileName: string; localFileName: string): Boolean;
procedure PKG_DelFile(archName: string; archFileName: string);
procedure PKG_FreeLib;
implementation

uses
  Windows, uMainForm, SysUtils;

type
  FUN_InitPacker = function(initPath: PChar; caheArkfile: Integer): Integer; stdcall;
  FUN_UpdateFile = function(archName: PChar; archFileName: PChar; localFileName: PChar; notUsed: Integer): Integer; stdcall;
  FUN_DelFile = function(archName: PChar; archFileName: PChar): Integer; stdcall;
  FUN_UninitPacker = function(): Integer; stdcall;
var
  _H: HMODULE;
  _InitPacker: FUN_InitPacker;
  _UpdateFile: FUN_UpdateFile;
  _DelFile: FUN_DelFile;
  _UninitPacker: FUN_UninitPacker;

procedure PKG_InitLib;
begin
  if _H=0 then
  begin
    _H := LoadLibrary(PChar(AppPath + S_Packer));
    if _H=0 then raise Exception.Create('load ' + S_Packer + ' error!');
    @_InitPacker := GetProcAddress(_H, 'initPacker');
    @_UpdateFile := GetProcAddress(_H, 'updateFile');
    @_DelFile := GetProcAddress(_H, 'delFile');
    @_UninitPacker := GetProcAddress(_H, 'uninitPacker');
    if Assigned(@_InitPacker) and Assigned(@_UpdateFile)
      and Assigned(@_DelFile) and Assigned(@_UninitPacker) then
    begin
      _InitPacker(PChar(AppPath), 0);
    end else
    begin
      FreeLibrary(_H);
      _H := 0;
      raise Exception.Create('load ' + S_Packer + ' error!');
    end;
  end;
end;

function PKG_UpdateFile(archName: string; archFileName: string; localFileName: string): Boolean;
var
  updateRet: Integer;
begin
  PKG_InitLib;
  updateRet := _UpdateFile(PChar(archName), PChar(archFileName), PChar(localFileName), 0);
  result := updateRet=0;

  if not result then
  begin
    raise Exception.Create('UpdateFile ' + localFileName + ' error! ret=' + IntToStr(updateRet));
  end;
end;

procedure PKG_DelFile(archName: string; archFileName: string);
begin
  PKG_InitLib;
  _DelFile(PChar(archName), PChar(archFileName));
end;

procedure PKG_FreeLib;
begin
  if _H<>0 then
  begin
    _UninitPacker;
    FreeLibrary(_H);
    _H := 0;
  end;
end;

initialization
  _H := 0;

finalization
  PKG_FreeLib;
end.
